const config=require('../config/config');
const crypto=require('crypto');
const events=require('events');
const router=require('koa-router')();
const passport=require('koa-passport');
const _=require('underscore');
const {User}=require('../modles/index');
const isLoggedout=require('../middlewares/isLoggedout');

router.get('/github',isLoggedout(),passport.authenticate('github'));

router.get('/github/callback',isLoggedout(),(ctx,next)=>{
    return passport.authenticate('github',async (err, user, token)=>{
        //console.log('callback:',user,token);
        if (err) return next(err);
        if (!user) {
            ctx.flash={error:'Github验证错误'};
            return ctx.redirect('/login');
        }

        let same=await User.findOne({username:user.username});

        let ee=new events();
        ee.on('success',(user={},msg='Github验证成功')=>{
            ctx.logIn(_.pick(user,'_id','username','githubId','avatar','regTimeStr'), (err)=>{
                if (err) return next(err);
                ctx.flash={success:msg};
                ctx.redirect('/');
            });
        });
        if(same){//用户名已经注册
            if(same.githubId){//Github认证用户
                return ee.emit('success',same);
            }else{//本地注册用户（需要绑定本地帐号）
                ctx.flash={success:'验证成功，绑定帐号',third:{title:'github',userid:user.id,username:user.username,avatar:user._json.avatar_url}};
                return ctx.redirect('/auth/bundling');
            }
        }

        //新Github认证用户
        let newUser=new User({
            username:user.username,
            password:crypto.createHash('md5').update([user.id,user.username,config.secret].join()).digest('hex'),
            githubId:user.id,
            avatar:user._json.avatar_url,
            regTime:new Date()
        });
        await newUser.save();
        ee.emit('success',newUser);
    })(ctx,next);
});

router.get('/bundling',isLoggedout(),async ctx=>{
    let third=ctx.flash.third;
    await ctx.render('bundling',{
        title:[ctx.locals.name,'Home'].join('-'),
        third,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});
router.post('/bundling',isLoggedout(),async (ctx,next)=>{
    let {username,password,third_title,third_userid,third_username,third_avatar}=ctx.request.body,ee=new events();
    ee.on('fail',msg=>{
       ctx.flash={error:msg,third:{title:third_title,userid:third_userid,username:third_username,avatar:third_avatar}};
       ctx.redirect('back');
    });

    if(!username || !password)return ee.emit('fail','用户名或密码未输入');

    let user=await User.findOne({username});//查找通过本地注册的同名用户
    if(!user)return ee.emit('fail','用户名或密码错误-1');
    if(user.password !== crypto.createHash('md5').update([password,config.secret].join()).digest('hex'))return ee.emit('fail','用户名或密码错误-2');

    await User.update({username},{githubId:third_userid,avatar:third_avatar});

    ctx.flash={success:'绑定成功'};
    ctx.logIn(Object.assign(_.pick(user,'_id','username','githubId','avatar','regTimeStr'),{githubId:third_userid,avatar:third_avatar}), (err)=>{
        if (err) return next(err);
        ctx.flash={success:'绑定成功'};
        ctx.redirect('/');
    });
});


module.exports=router;

